﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QLGT_2.Models;
using System.Data.Entity;
using System.Web.Security;

namespace QLGT_2.Controllers
{
    public class HomeController : Controller
    {
        QLGTContext db = new QLGTContext();

        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult Login()
        {
            HttpCookie ckMatKhau = Request.Cookies["MatKhau"];
            HttpCookie ckTenDangNhap = Request.Cookies["TenDangNhap"];
            if (ckTenDangNhap != null)
            {
                int id = CheckLogin(ckTenDangNhap.Value, ckMatKhau.Value, true);

                if (id == 1)
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        int CheckLogin(string TenDangNhap, string MatKhau, bool remember = false)
        {
            if (TenDangNhap != null && MatKhau != null)
            {
                string MatKhauMd5 = DuLieuChung.MaHoaMD5(MatKhau);

                //var users = (from p in db.TbNguoiDungs
                //             where p.TenDangNhap == TenDangNhap && p.MatKhau == MatKhauMd5
                //             select p
                //            ).ToList();
                var users = (from p in db.tbl_NguoiDungs
                             where p.TenDangNhap == TenDangNhap && p.MatKhau == MatKhauMd5
                             select p
                            );

                if (users.Count() == 0)
                {
                    ModelState.AddModelError("Error", "Tên đăng nhập hoặc mật khẩu không đúng.");
                    return 0;
                }

                //TbNguoiDung user = users.First();

                if (users.First().KhoaTaiKhoan == KhoaTaiKhoan.Khoa)
                {
                    ModelState.AddModelError("Error", "Tài khoản của bạn bị khóa.");
                    return 0;
                }

                if (remember)
                {
                    // check if cookie exists and if yes update
                    HttpCookie ckTenDangNhap = Request.Cookies["TenDangNhap"];


                    if (ckTenDangNhap != null)
                    {
                        //force to expire it
                        ckTenDangNhap.Values.Add("TenDangNhap", users.First().TenDangNhap);
                        ckTenDangNhap.Values.Add("MatKhau", MatKhau);
                        ckTenDangNhap.Values.Add("QUyen", users.First().MaQuyen.ToString());
                        ckTenDangNhap.Expires = DateTime.Now.AddHours(-20);
                    }

                    //create a cookie
                    ckTenDangNhap = new HttpCookie("TenDangNhap");
                    HttpCookie ckMatKhau = new HttpCookie("MatKhau");
                    HttpCookie ckQuyen = new HttpCookie("Quyen");
                    ckTenDangNhap.Value = TenDangNhap;
                    ckMatKhau.Value = MatKhau;
                    ckQuyen.Value = users.First().MaQuyen.ToString();
                    ckTenDangNhap.Expires = DateTime.Today.AddDays(15);
                    ckMatKhau.Expires = DateTime.Today.AddDays(15);
                    ckQuyen.Expires = DateTime.Today.AddDays(15);
                    Response.Cookies.Add(ckTenDangNhap);
                    Response.Cookies.Add(ckMatKhau);
                    Response.Cookies.Add(ckQuyen);

                    //FormsAuthentication.SetAuthCookie(TenDangNhap, false);
                }

                Session["TenDangNhap"] = users.First().TenDangNhap;
                Session["Quyen"] = users.FirstOrDefault().MaQuyen;
                //string x = db.tbl_Quyens.Where(m => m.MaQuyen == users.FirstOrDefault().MaQuyen).FirstOrDefault().Quyen;
                return 1;
            }
            return 0;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(string TenDangNhap, string MatKhau, bool remember = false)
        {
            if (ModelState.IsValid && TenDangNhap != null && MatKhau != null)
            {
                int id = CheckLogin(TenDangNhap, MatKhau, remember);

                if (id == 1)
                {
                    return RedirectToAction("Index", "Home");
                }
                return View();
            }
            return View();
            //HttpCookie ckMatKhau = Request.Cookies["MatKhau"];
            //HttpCookie ckTenDangNhap = Request.Cookies["TenDangNhap"];
            //if (ckTenDangNhap != null)
            //{
            //    int id = CheckLogin(ckTenDangNhap.Value, ckMatKhau.Value, true);

            //    if (id == 3)
            //    {
            //        return RedirectToAction("Profile", "Home");
            //    }
            //    else
            //        if (id == 1)
            //            return RedirectToRoute("Admin", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
            //}
            //return View();
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            // replace with username if this is the wrong cookie name
            Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            Session.Clear();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
            Response.Cache.SetNoStore();
            Response.AppendHeader("Pragma", "no-cache");

            // send an expired cookie back to the browser
            var ticketExpiration = DateTime.Now.AddDays(-7);
            var ticket = new FormsAuthenticationTicket(
                1,
                // replace with username if this is the wrong cookie name
                FormsAuthentication.FormsCookieName,
                DateTime.Now,
                ticketExpiration,
                false,
                String.Empty);
            var ckTenDangNhap = new System.Web.HttpCookie("TenDangNhap")
            {
                Expires = ticketExpiration,
                Value = FormsAuthentication.Encrypt(ticket),
                HttpOnly = true
            };
            var ckMatKhau = new System.Web.HttpCookie("MatKhau")
            {
                Expires = ticketExpiration,
                Value = FormsAuthentication.Encrypt(ticket),
                HttpOnly = true
            };
            var ckQuyen = new System.Web.HttpCookie("Quyen")
            {
                Expires = ticketExpiration,
                Value = FormsAuthentication.Encrypt(ticket),
                HttpOnly = true
            };

            Response.Cookies.Add(ckTenDangNhap);
            Response.Cookies.Add(ckMatKhau);
            Response.Cookies.Add(ckQuyen);

            return RedirectToAction("Login", "Home");
        }


    }
}
